import styles from "@pages/home/widgets/news/styles/styles.module.less";
import { Link } from "react-router-dom";
import GeekIcon from "@shared/geekIcon";
import NewsItem from "@pages/home/widgets/news/widgets/Item";
import { useEffect } from "react";
import { useLazyRequestNewsQuery } from "@service/news";
import { useTypedDispatch, useTypedSelector } from "@store/index";
import { saveNews, selectChannelNews } from "@slice/news";
import Infinite from "@shared/infinite";
import { useParams } from "react-router-dom";

import { saveDistance } from "@slice/news";
import { useOutletContext } from "react-router-dom";
import { MainLayoutOutletProps } from "@shared/mainLayout";

export default function News() {
    // 获取路由参数
    const cid = useParams().cid!;
    // 用于获取新闻列表
    const [requestNews] = useLazyRequestNewsQuery();
    // 获取 dispatch 方法
    const dispatch = useTypedDispatch();
    // 获取新闻列表
    const channelNews = useTypedSelector(selectChannelNews(cid));

    // 新闻列表加载方法
    const loadMore = () => {
        // 发送请求获取新闻列表
        return requestNews({
            channel_id: cid,
            timestamp: typeof channelNews === 'undefined' ? Date.now() + "" : channelNews.pre_timestamp
        })
            .unwrap()
            .then((response: any) => {
                // 获取服务端返回的新闻列表和下一页数据对应的时间戳
                const { pre_timestamp, results } = response.data;
                // 保存当前加载的新闻列表
                dispatch(saveNews({ cid, results, pre_timestamp }));
            });
    };
    // 用于获取滚动内容区域的距离、设置内容区域滚动距离
    const { getScrollTop, setContainerScrollTop } = useOutletContext<MainLayoutOutletProps>();

    useEffect(() => {
        // 页面进入后设置内容的滚动位置
        setContainerScrollTop(channelNews?.distance || 0);
        // 页面离开前
        return () => {
            // 记录页面内容的滚动位置
            dispatch(saveDistance({ cid, distance: getScrollTop() }));
        };
    }, [channelNews?.distance, cid, dispatch, getScrollTop, setContainerScrollTop]);

    return (
        <>
            <ul className={styles.news}>
                {channelNews?.results.map((news) => (
                    <NewsItem news={news} key={news.art_id} />
                ))}
            </ul>
            <Infinite hasMore={channelNews?.pre_timestamp !== null} loadMore={loadMore} />
        </>
    );
}